package org.zhang.shortlink.admin.common.biz.user;

import com.alibaba.fastjson2.JSON;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.zhang.shortlink.admin.common.constant.RedisConstant;
import org.zhang.shortlink.admin.common.constant.UserConstant;
import org.zhang.shortlink.admin.dto.req.UserInfoDTO;

import java.io.IOException;

@RequiredArgsConstructor
public class UserTransmitFilter implements Filter {

    private final StringRedisTemplate stringRedisTemplate;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String token = httpServletRequest.getHeader(UserConstant.USER_TOKEN_KEY);
        String username = httpServletRequest.getHeader(UserConstant.USER_NAME_KEY);
        if (token != null) {
            String jsonStr = (String) stringRedisTemplate.opsForHash().get(RedisConstant.USER_LOGIN+username, token);
            UserInfoDTO userInfoDTO = JSON.parseObject(jsonStr, UserInfoDTO.class);
            UserContext.setUser(userInfoDTO);
        }
        try {
            filterChain.doFilter(servletRequest, servletResponse);
        } finally {
            UserContext.removeUser();
        }
    }
}